package cn.stimd.spring.context.annotation;

import cn.stimd.spring.beans.factory.annotation.AnnotatedGenericBeanDefinition;
import cn.stimd.spring.beans.factory.support.BeanDefinitionRegistry;
import cn.stimd.spring.context.ApplicationContext;
import org.springframework.core.env.Environment;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class AnnotatedBeanDefinitionReader {
    private final BeanDefinitionRegistry registry;
    private ConditionEvaluator conditionEvaluator;
    private AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();

    public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
        this(registry, ((ApplicationContext)registry).getEnvironment());
    }


    public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
        this.registry = registry;
        this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
        AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
    }


    public void register(Class<?>... annotatedClasses) {
        for (Class<?> annotatedClass : annotatedClasses) {
            registerBean(annotatedClass, null);
        }
    }

    private void registerBean(Class<?> annotatedClass, String name) {
        AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
        //1. 根据条件判定Bean是否加载
        if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
            return;
        }

        //2. 根据@Role、@Primary等注解的信息来设置BeanDefinition的相关属性
        AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);

        //3. 注册BeanDefinition
        String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd));
        registry.registerBeanDefinition(beanName, abd);
    }


    public void setEnvironment(Environment environment) {
        this.conditionEvaluator = new ConditionEvaluator(this.registry, environment, null);
    }
}
